<template>
  <el-card>
    <div>
      <div style="margin: 10px 5px">
        <el-page-header @back="gotoIndex" style="font-size: 26px" title="返回首页" content="体检套餐管理">
        </el-page-header>
      </div>
      <div style="margin: 10px 5px">
        <el-button type="primary" @click="add">
          <i class="iconfont icon-r-add" style="font-size: 26px"></i>
          新增
        </el-button>
      </div>

      <div style="margin: 10px 5px">
        <label style="margin-right: 10px; margin-left: 20px">套餐名称：</label>
        <el-input v-model="search" style="width: 20%;" placeholder="请输入名称查询"/>
        <label style="margin-right: 10px; margin-left: 20px">套餐分类：</label>
        <el-select v-model="searchBycategoryId"
                   placeholder="请选择套餐分类"
                   @change="$forceUpdate()"
                   clearable>
          <el-option v-for="(item, index) in setMealList"
                     :key="index"
                     :label="item.name"
                     :value="item.id" />
        </el-select>
        <label style="margin-right: 10px; margin-left: 20px">套餐人群：</label>
        <el-select v-model="people"
                   placeholder="请输入名称查询"
                   @change="$forceUpdate()"
                   clearable>
          <el-option key="1" label="男性" value="1" />
          <el-option key="2" label="女性" value="2" />
        </el-select>
        <el-button style="margin-left: 10px" type="primary" @click="list">查询</el-button>.
      </div>

      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="体检套餐ID"/>
        <el-table-column prop="name" label="体检套餐名称"/>
        <el-table-column prop="people" label="套餐人群" :formatter="formaPeople" />
        <el-table-column prop="image"
                         label="图片">
          <template slot-scope="{ row }">
            <el-image style="width: 80px; height: 40px; border: none; cursor: pointer"
                      :src="row.image">
              <div slot="error"
                   class="image-slot">
                <img src="../assets/noImg.png"
                     style="width: auto; height: 40px; border: none">
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="setmealChecks" label="体检包含项目" >
          <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.setmealChecks" :key="index">
            {{ item.name }}
          <span v-if="index !== scope.row.setmealChecks.length - 1">, </span>
        </span>
          </template>
        </el-table-column>
        <el-table-column prop="categoryName" label="体检套餐分类" />
        <el-table-column prop="price" label="套餐价格费用" />
        <el-table-column prop="status" label="状态" >
          <template slot-scope="scope">
            <el-tag type="success" v-if="String(scope.row.status) === '1'"
            >启用</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间"/>
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button
                type="text"
                size="small"
                class="blueBug"
                @click="handleEdit(scope.row)" >
              编辑
            </el-button>
            <el-button
                type="text"
                size="small"
                class="non"
                :class="{
                blueBug: scope.row.status === 0,
                delBut: scope.row.status !== 0,
              }"
                @click="statusHandle(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
                size="small"
                type="text"
                class="delBut"
                @click="handleDel(scope.row)" >
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>


      <el-dialog title="提示" :visible.sync="dialogVisible">
        <el-form :model="form" :rules="rules" ref="form" label-width="120px">

          <el-form-item label="体检套餐名称:"  label-width="120px" prop="name">
            <el-input v-model="form.name" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="套餐人群:"  label-width="120px" prop="people">
            <el-select v-model="form.people"
                       placeholder="请输入名称查询"
                       @change="$forceUpdate()"
                       style="width: 80%"
                       clearable>
              <el-option key="1" label="男性" value="1" />
              <el-option key="2" label="女性" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="套餐费用" label-width="120px" prop="price">
            <el-input v-model="form.price" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="套餐包含项目" label-width="120px" prop="checksIds">
            <el-select
                v-model="form.checksIds"
                multiple
                placeholder="请选择"
            >
              <el-option
                  v-for="item in options"
                  :key="item.checkId"
                  :label="item.name"
                  :value="item.checkId"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="体检套餐分类:"  label-width="120px" prop="categoryId">
            <el-select v-model="form.categoryId"
                       placeholder="请选择套餐分类"
                       @change="$forceUpdate()">
              <el-option v-for="(item, index) in setMealList"
                         :key="index"
                         :label="item.name"
                         :value="item.id" />
            </el-select>
          </el-form-item>

          <div>
            <el-form-item label="套餐图片:"
                          required
                          prop="image">
              <image-upload
                  :prop-image-url="form.image"
                  @imageChange="imageChange">
                图片大小不超过2M<br>仅能上传 PNG JPEG JPG类型图片<br>建议上传200*200或300*300尺寸的图片
              </image-upload>
            </el-form-item>
          </div>
          <el-form-item label="套餐描述:" prop="description">
            <el-input v-model="form.description"
                      type="textarea"
                      :rows="3"
                      maxlength="200"
                      placeholder="套餐描述，最长200字" />
          </el-form-item>
        </el-form>
        <template #footer>
        <span  slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          <i class="iconfont icon-r-left" style="font-size: 20px;"></i> 取 消</el-button>
        <el-button type="primary" @click="save">
          <i class="iconfont icon-r-yes" style="font-size: 20px;"></i>确 定</el-button>
        </span>
        </template>
      </el-dialog>


      <div style="margin: 10px 0">
        <el-pagination
            @size-change="handlePageSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3,5,10,15]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">

        </el-pagination>
      </div>

    </div>
  </el-card>
</template>

<script>

import request from "@/utils/request";
import ImageUpload from "@/components/ImgUpload";
export default {
  components: {
    ImageUpload
  },
  data(){
    return{
      //存放表单数据
      form: {},
      //默认设置提示表单为不可见
      dialogVisible: false,
      //默认设置表格数据位空
      tableData: [],
      //多选选择器
      options: [],
      //默认设置分类选择框数据位空
      setMealList: [],
      searchBycategoryId : '',
      people: "",
      //默认设置图片地址为空
      imageUrl: '',
      //默认设置搜索数据位空
      search:'',
      //分页相应数据绑定
      currentPage:1,//当前页
      pageSize:3,//每页显示数据数
      total:10,//共多少条数据
      //表单效验规则
      rules:{
        name:[
          {required: true, message: "请输入名称", trigger: "blur"}
        ],
        description: [
          {required: true, message: "请输入描述", trigger: "blur"},
          {max: 200,message: "套餐描述，最长200字", trigger: "blur"}
        ],
        price: [
          {required: true, message: "请输入费用", trigger: "blur"},
          //使用正则表达式输入的数据进行校验=> java基础我们讲过正则表达式
          {pattern: /^([1-9]\d*|0)(\.\d+)?$/, message: "请输入数字", trigger: "blur"}
        ],
        categoryId: [
          {required: true, message: "请输入分类", trigger: "blur"}
        ],
      }

    }
  },
  created() {

    this.getcategoryName();
    this.list();//调用list方法
  },
  methods:{
    formaPeople(row){
      return row.people === '1' ? '男性' : row.people === '2' ? '女性' : '性别不限';
    },
    gotoIndex(){
      this.$router.push("/adminLayout");
    },
    getCheck(){
      request.get("/api/check/list").then(res=>{
        console.log("checkoptions",res.data.data);
        if(res.data.code == 1){
          this.options = res.data.data.map(item=>({
            checkId : item.id,
            name: item.name,
            price: item.price,
            setmealId: this.form.id
          }))
        }
      })
    },

    getcategoryName(){
      request.get("/api/category/list").then(res=>{
        console.log("list",res.data.data);
            if(res.data.code == 1){
              this.setMealList = res.data.data
            }
      })
    },
    add() {
      this.dialogVisible = true;
      console.log("visible,",this.dialogVisible)
      this.form = {};
      if (this.$refs.form?.resetFields) {
        this.$refs.form.resetFields();
      }
      this.getCheck();
    },
    save() {
      if(this.form.id){
        this.$refs['form'].validate((valid)=>{
          console.log("valid",valid);
          if(valid){//进行效验,通过
            request.put("/api/setmeal", this.form).then(res => {
              console.log(res)
              if(res.data.code == 1){
                this.$message({
                  type:"success",
                  message:"更新成功"
                })
                this.dialogVisible = false;
                //调用list方法, 刷新数据
                this.list();
              }else  {
                this.$message({
                  type:"error",
                  message: res.data.msg
                })
                this.dialogVisible = false;
                //调用list方法, 刷新数据
                this.list();
              }
            }).catch(err => {
              this.$message.error('请求出错了：' + err.message)
            })
          }else {//效验没通过
            return false;
          }
        })

      }else{
        this.$refs['form'].validate((valid)=>{
          //测试前端效验放行
          //valid=true
          console.log("valid",valid)
          if(valid){//进行效验,通过
            console.log("this.form",this.form)
            request.post("/api/setmeal", this.form).then(res => {
              console.log(res)
              if(res.data.code==1){

                this.$message({
                  type:"success",
                  message:"新增成功"
                })
                this.dialogVisible = false;
                //调用list方法, 刷新数据
                this.list();
              }else {
                this.$message({
                  type:"error",
                  message: res.data.msg
                })
                this.dialogVisible = false;
                //调用list方法, 刷新数据
                this.list();
              }
            }).catch(err => {
              this.$message.error('请求出错了：' + err.message)
            })
          }else {//效验没通过
            this.$message({
              type:"error",
              message:"验证失败,不提交"
            })
            return false;
          }
        })
        // =======说明====...

      }

    },
    list() {
      request.get("/api/setmeal/page",{
        params:{//指定请求携带的参数
          page:this.currentPage,
          pageSize:this.pageSize,
          name:this.search,
          categoryId: this.searchBycategoryId,
          people: this.people
        }}).then(res => {
        console.log("res-",res)
        //绑定 tableData, 显示在表格
        this.tableData =res.data.data.records
        this.total=res.data.data.total
      })
    },
    handleEdit(row){
      console.log("row=",row)
      if (this.$refs.form?.resetFields) {
        this.$refs.form.resetFields();
      }
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible= true
      this.getCheck();

    },
    statusHandle(row){
      var status
      if(row.status == 1){
        status=0
      }else {
        status=1
      }
      this.$confirm('确认更改状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() =>{
        request.post(
            "/api/setmeal/status/"+ status+ "?id=" +row.id
        ).then(res => {
          console.log("statusres,",res)
          if(res.data.code == 1){
            this.$message({
              type:"success",
              message:"更改成功"
            })
          }else {
            this.$message({
              type:"error",
              message: res.data.msg
            })
          }
          this.list()
        }).catch(err => {
          this.$message.error('请求出错了：' + err.message)
        })
      })
    },
    handleDel(row){
      this.$confirm('确认删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() =>{
        request.delete("/api/setmeal",{
          params:{//指定请求携带的参数
            id: row.id
          }}).then(res => {
          console.log("deleteres,",res)
          if(res.data.code == 1){
            this.$message({
              type:"success",
              message:"删除成功"
            })
          }else {
            this.$message({
              type:"error",
              message: res.data.msg
            })
          }
          this.list()
        }).catch(err => {
          this.$message.error('请求出错了：' + err.message)
        })
      })

    },
    handleCurrentChange(pageNum){//处理分页请求
      //当用户点击分页超链接时会携带pageNum
      console.log("pageNum",pageNum)
      this.currentPage=pageNum
      //发出分页请求
      this.list()
    },
    handlePageSizeChange(pageSize){
      console.log("pageSize",pageSize)
      this.pageSize=pageSize
      this.list()
    },
    imageChange(value) {
      this.form.image = value
    },


  }
}

</script>
<style scoped lang="scss">
.el-table {
  margin-top: 20px;
  margin-bottom: 20px;
}
.el-form {
  margin-top: 0;
}
.disabled-text {
  color: #bac0cd !important;
}
.blueBug {
  color: #419EFF !important;
  position: relative;
}
.addCheck {
  .el-input {
    width: 130px;
  }

  .el-input-number__increase {
    border-left: solid 1px #fbe396;
    background: #fffbf0;
  }

  .el-input-number__decrease {
    border-right: solid 1px #fbe396;
    background: #fffbf0;
  }

  input {
    border: 1px solid #fbe396;
  }

  .table {
    border: solid 1px #ebeef5;
    border-radius: 3px;

    th {
      padding: 5px 0;
    }

    td {
      padding: 7px 0;
    }
  }
}
.addBut {
  background: #ffc200;
  display: inline-block;
  padding: 0px 20px;
  border-radius: 3px;
  line-height: 40px;
  cursor: pointer;
  border-radius: 4px;
  color: #333333;
  font-weight: 500;
}
.blueBug::after {
  content: '';
  position: absolute;
  right: -6px;
  height: 14px;
  width: 0px;
  border-right: solid 1px #EBEEF5 !important;
}

.delBut {
  color: #F56C6C !important;
  position: relative;
}

.delBut::after {
  content: '';
  position: absolute;
  right: -6px;
  height: 14px;
  width: 0px;
  border-right: solid 1px #EBEEF5 !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


